package com.qiantu.phone.ui.adapter;

import android.content.Context;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.qiantu.api.BuildConfig;
import com.qiantu.api.db.LLRoomDBManager;
import com.qiantu.api.entity.DeviceBean;
import com.qiantu.api.utils.ThemeUtil;
import com.qiantu.phone.R;
import com.qiantu.phone.app.AppAdapter;
import com.qiantu.phone.app.AppApplication;
import com.qiantu.phone.event.RoomIconSelectEvent;
import com.qiantu.phone.glide.GlideApp;
import com.qiantu.phone.ui.activity.SelectDeviceActivity;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 *    author : Android 轮子哥
 *    github : https://github.com/getActivity/AndroidProject
 *    time   : 2019/09/22
 *    desc   : 状态数据列表
 */
public final class ManagerDeviceAdapter extends AppAdapter<DeviceBean> {

    private Map<String, DeviceBean> selected = new LinkedHashMap<>();
    private List<String> selectedDeviceSerialNo;
    private boolean selectable;
    private boolean isSingleSelect;
    private int selectType = 0;
    private boolean onlySeeCommonly = false;
    private boolean isDeviceAction = false;
    private boolean showOffline = false;
    private List<DeviceBean> allDevice;
    private Map<String,Integer> taskData;

//    private List<DeviceBean> favouriteDevice;

    public ManagerDeviceAdapter(Context context) {
        super(context);
    }

    public ManagerDeviceAdapter(Context context,Map<String,Integer> taskData) {
        super(context);
        this.taskData = taskData;
    }

    public ManagerDeviceAdapter(Context context,int selectType) {
        super(context);
        this.selectType = selectType;
    }

    public ManagerDeviceAdapter(Context context, boolean selectable, boolean isSingleSelect) {
        super(context);
        this.selectable = selectable;
        this.isSingleSelect = isSingleSelect;
    }

    public ManagerDeviceAdapter(Context context, boolean selectable, boolean isSingleSelect,int selectType) {
        super(context);
        this.selectable = selectable;
        this.isSingleSelect = isSingleSelect;
        this.selectType = selectType;
    }

    public void setOnlySeeCommonly(boolean onlySeeCommonly) {
        this.onlySeeCommonly = onlySeeCommonly;
        if (allDevice != null){
            if (onlySeeCommonly){
                setData(getFavouriteDevice());
            }else {
                setData(allDevice);
            }
        }
        notifyDataSetChanged();
    }

    public void setTotalData(List<DeviceBean> data){
        allDevice = data;
        if (onlySeeCommonly){
            setData(getFavouriteDevice());
        }else {
            setData(allDevice);
        }
    }

    @Override
    public void setData(@Nullable List<DeviceBean> data) {
        if(selectedDeviceSerialNo != null && data != null){
            for(String deviceSerialNo : selectedDeviceSerialNo){
                for(DeviceBean device : data){
                    if(device.getDeviceSerialNo().equals(deviceSerialNo)){
                        this.selected.put(device.getDeviceSerialNo(), device);
                        break;
                    }
                }
            }
        }
        super.setData(data);
    }

    public void setAllSelect(@Nullable Boolean allSelect) {
        if(allSelect){
            for(DeviceBean deviceBean : allDevice){
                if(!selected.containsKey(deviceBean.getDeviceSerialNo())){
                    selected.put(deviceBean.getDeviceSerialNo(),deviceBean);
                }
            }
        }else{
            for(DeviceBean deviceBean : allDevice){
                if(selected.containsKey(deviceBean.getDeviceSerialNo())){
                    selected.remove(deviceBean.getDeviceSerialNo());
                }
            }
        }
        notifyDataSetChanged();
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        return new ViewHolder();
    }

    private final class ViewHolder extends AppAdapter<?>.ViewHolder {

        private final View contentView;
        private final ImageView icon;
        private final CheckBox checkbox;
        private final TextView tvName;
        private final TextView tvOffline;
        private final TextView tvFloorRoomName;
        private final ImageView tvDeviceFlag;
        private final View btnDeleteDeviceAction;
        private final FrameLayout sortAction;
        private final TextView sortText;
        private TextView tvNum;

        private ViewHolder() {
            super(R.layout.manager_device_item);
            contentView = findViewById(R.id.content_view);
            icon = findViewById(R.id.icon);
            checkbox = findViewById(R.id.checkbox);
            tvName = findViewById(R.id.tv_name);
            tvOffline = findViewById(R.id.tv_offline);
            tvFloorRoomName = findViewById(R.id.floor_room_name);
            tvDeviceFlag = findViewById(R.id.tv_device_flag);
            btnDeleteDeviceAction = findViewById(R.id.btn_delete_device_action);
            sortAction = findViewById(R.id.btn_sort_device_action);
            sortText = findViewById(R.id.btn_sort_device_text);
            tvNum = findViewById(R.id.tv_add_num);
            checkbox.setOnClickListener(this);
        }

        @Override
        public void onClick(View view) {
            //可选中状态item和checkbox都可用点击选中
            if(selectable){
                int position = getViewHolderPosition();
                if (position < 0 || position >= getItemCount()) {
                    return;
                }
                DeviceBean data = (DeviceBean) itemView.getTag();
                if (view == itemView) {
                    checkbox.setChecked(!checkbox.isChecked());
                }
                if (isSingleSelect){
                    if (checkbox.isChecked()){
                        for (int i = 0; i < getData().size(); i++) {
                            DeviceBean device = getData().get(i);
                            if (selected.get(device.getDeviceSerialNo()) != null) {
                                selected.clear();
                                notifyItemChanged(i);
                            }
                        }
                        selected.clear();
                        selected.put(data.getDeviceSerialNo(), data);
                    }
                }else {
                    if (checkbox.isChecked()) {
                        selected.put(data.getDeviceSerialNo(), data);
                    } else {
                        selected.remove(data.getDeviceSerialNo());
                    }
                }
                if (getChildClickListeners() != null) {
                    OnChildClickListener listener = getChildClickListeners().get(checkbox.getId());
                    if (listener != null) {
                        listener.onChildClick(getRecyclerView(), checkbox, position);
                    }
                }
                checkAllSelect();
            }else{
                super.onClick(view);
            }
        }

        @Override
        public void onBindView(int position) {
            DeviceBean device = getItem(position);
            String imageUrl;
//            switch (ThemeUtil.themeId){
//                case ThemeUtil.THEME_ORANGE:
                    imageUrl = BuildConfig.APP_RESOURCE_BASE + ThemeUtil.getIconThemeSuffix() + device.getImageUrl() + "_on_home.png";
//                    break;
//                default:
//                    imageUrl = device.getOnImageUrl();
//                    break;
//            }
            if(taskData != null && taskData.get(device.getDeviceSerialNo()) != null){
                tvNum.setVisibility(View.VISIBLE);
                tvNum.setText("已添加" + taskData.get(device.getDeviceSerialNo()));
            }else{
                tvNum.setVisibility(View.GONE);
            }
            GlideApp.with(icon).load(imageUrl).into(icon);
            tvName.setText(device.getName());
            if(device.getLinkType() == 3){
                tvFloorRoomName.setText(device.getFloorName());
            }else{
                tvFloorRoomName.setText(LLRoomDBManager.getInstance(getContext()).getFloorRoomName(device.getRoomSerialNo()));
            }

            if(device.getIsDisable()){
                tvDeviceFlag.setEnabled(false);
                tvDeviceFlag.setVisibility(View.VISIBLE);
                tvDeviceFlag.setImageDrawable(AppApplication.getInstance().getDrawable(R.mipmap.icon_device_unable));
            }else{
                if(device.getIsFavourite()){
                    tvDeviceFlag.setEnabled(true);
                    tvDeviceFlag.setVisibility(View.VISIBLE);
                    tvDeviceFlag.setImageDrawable(AppApplication.getInstance().getDrawable(R.mipmap.icon_device_favorite));
                }else{
                    tvDeviceFlag.setVisibility(View.GONE);
                }
            }
            if(selected.get(device.getDeviceSerialNo()) != null){
                if(isDeviceAction){
                    contentView.setSelected(true);
                    btnDeleteDeviceAction.setVisibility(View.VISIBLE);
                }else{
                    checkbox.setChecked(true);
                }
            }else{
                if(isDeviceAction){
                    contentView.setSelected(false);
                    btnDeleteDeviceAction.setVisibility(View.GONE);

                }else{
                    checkbox.setChecked(false);
                }
            }
            if((selectType == 2 || selectType == 3 || selectType == 4) && device.getTemporary() != null){
                sortText.setText(device.getTemporary().toString());
                sortAction.setVisibility(View.VISIBLE);
            }else{
                sortAction.setVisibility(View.GONE);
            }
            itemView.setTag(device);
            if(selectable){
                checkbox.setVisibility(View.VISIBLE);
                if(isSingleSelect){
                    checkbox.setCompoundDrawablesWithIntrinsicBounds(R.drawable.theme_single_check, 0, 0, 0);
                }else{
                    checkbox.setCompoundDrawablesWithIntrinsicBounds(R.drawable.theme_multiple_check, 0, 0, 0);
                }
            }else{
                checkbox.setVisibility(View.GONE);
            }
            if(!showOffline){
                tvOffline.setVisibility(View.GONE);
            }else{
                tvOffline.setVisibility(device.getIsOnline() ? View.GONE : View.VISIBLE);
            }
            if(device.getDeviceGroup() == 1){//特殊处理灯组没有不在线
                tvOffline.setVisibility(View.GONE);
            }
        }
    }

    public void checkAllSelect(){
        boolean allSelect = true;
        for(DeviceBean deviceBean : allDevice){
            if(!selected.containsKey(deviceBean.getDeviceSerialNo())){
                allSelect = false;
                break;
            }
        }
        if(subClickListener != null){
            subClickListener.OntopicClickListener(allSelect);
        }
    }

    public ArrayList<DeviceBean> getSelectedData() {
        ArrayList<DeviceBean> checkList = new ArrayList<>();
        for(String key : selected.keySet()){
            checkList.add(selected.get(key));
        }
        return checkList;
    }

    public boolean isSelected(DeviceBean device){
        return selected.get(device.getDeviceSerialNo()) != null;
    }

    public int getSelectedSize() {
        if(selected == null){
            return 0;
        }else{
            return selected.size();
        }
    }

    public void checkSelected(List<DeviceBean> selected){
        if(selected != null){
            for(DeviceBean data : selected){
                this.selected.put(data.getDeviceSerialNo(), data);
            }
            notifyDataSetChanged();
        }
    }

    public void checkSelectedBySerialNo(List<String> selected){
        this.selectedDeviceSerialNo = selected;
        if(selected != null && getData() != null){
            for(String deviceSerialNo : selected){
                for(DeviceBean device : getData()){
                    if(device.getDeviceSerialNo().equals(deviceSerialNo)){
                        this.selected.put(device.getDeviceSerialNo(), device);
                        break;
                    }
                }
            }
            notifyDataSetChanged();
        }
    }

    public void checkSelected(DeviceBean selected){
        if(selected != null){
            this.selected.put(selected.getDeviceSerialNo(), selected);
            notifyDataSetChanged();
        }
    }

    public void setSelected(List<DeviceBean> selected){
        if(selected != null){
            for(DeviceBean data : selected){
                this.selected.put(data.getDeviceSerialNo(), data);
            }
        }
    }

    public void removeSelected(String deviceSerialNo){
        if(selected != null){
            this.selected.remove(deviceSerialNo);
            notifyDataSetChanged();
        }
    }

    public void setSelectedAll(boolean isAllSelect){
        if(isAllSelect){
            for(DeviceBean data : getData()){
                selected.put(data.getDeviceSerialNo(), data);
            }
        }else{
            selected.clear();
        }
        notifyDataSetChanged();
    }

    public void setSelectable(boolean selectable){
        this.selectable = selectable;
        selected.clear();
        notifyDataSetChanged();
    }

    public void setSingleSelect(boolean selectable){
        this.isSingleSelect = selectable;
    }

    public void setIsDeviceAction(boolean isDeviceAction){
        this.isDeviceAction = isDeviceAction;
    }

    public void setShowOffline(boolean showOffline){
        this.showOffline = showOffline;
    }

    public boolean isSelectable() {
        return selectable;
    }

    private List<DeviceBean> getFavouriteDevice(){
        List<DeviceBean> commonBean = new ArrayList<>();
        for (DeviceBean bean : allDevice){
            if (bean.getIsFavourite()){
                commonBean.add(bean);
            }
        }
        return commonBean;
    }

    public void update(DeviceBean newDevice) {
        for (int i = 0; i < getData().size(); i++) {
            DeviceBean device = getData().get(i);
            //设备号相同并且deviceType相同才进入
            if (!TextUtils.isEmpty(device.getDeviceSerialNo())
                    && device.getDeviceSerialNo().equals(newDevice.getDeviceSerialNo())) {
                //在线状态不一样或者deviceType或者设备首页属性不一致才刷新
                if(device.getIsOnline() != newDevice.getIsOnline()
                        || !device.getImageUrl().equals(newDevice.getImageUrl())
                        || !device.getName().equals(newDevice.getName())
                        || !device.getRoomSerialNo().equals(newDevice.getRoomSerialNo())
                        || !device.getDeviceType().equals(newDevice.getDeviceType())
                        || !device.getStateData().getStatus().homeDeviceEquals(newDevice.getStateData().getStatus())){
                    getData().set(i, newDevice);
                    notifyItemChanged(i);
                }
                break;
            }
        }
    }

    public void update(List<DeviceBean> devices) {
        if(getData() != null){
            return;
        }
        for (int i = 0; i < getData().size(); i++) {
            DeviceBean device = getData().get(i);
            for(int j = 0; j<devices.size(); j++){
                if (!TextUtils.isEmpty(device.getDeviceSerialNo())
                        && device.getDeviceSerialNo().equals(devices.get(j).getDeviceSerialNo())) {
                    if(device.getIsOnline() != devices.get(j).getIsOnline()
                            || !device.getImageUrl().equals(devices.get(j).getImageUrl())
                            || !device.getName().equals(devices.get(j).getName())
                            || !device.getRoomSerialNo().equals(devices.get(j).getRoomSerialNo())
                            || !device.getDeviceType().equals(devices.get(j).getDeviceType())
                            || !device.getStateData().getStatus().homeDeviceEquals(devices.get(j).getStateData().getStatus())){
                        getData().set(i, devices.get(j));
                    }
                    break;
                }
            }
        }
    }

    private SubClickListener subClickListener;
    public void setSubClickListener(SubClickListener topicClickListener) {
        this.subClickListener = topicClickListener;
    }

    public interface SubClickListener {
        void OntopicClickListener(boolean isAllSelect);
    }


}